<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <!-- 商品数据 ID -->
      <uni-forms-item name="data_id" label="商品数据ID" required>
        <uni-easyinput
          placeholder="请输入商品数据的唯一 ID"
          v-model="formData.data_id"
          trim="both"
        ></uni-easyinput>
      </uni-forms-item>
      <!-- 商品名称 -->
      <uni-forms-item name="name" label="商品名称" required>
        <uni-easyinput
          placeholder="请输入商品名称"
          v-model="formData.name"
          trim="both"
        ></uni-easyinput>
      </uni-forms-item>
      <!-- 商品图片 -->
      <uni-forms-item name="images" label="商品图片列表">
        <uni-file-picker
          file-mediatype="image"
          return-type="object"
          v-model="formData.images"
          @after-read="uploadImages"
        ></uni-file-picker>
      </uni-forms-item>
      <!-- 所属基础分类 ID -->
      <!-- 所属基础分类 -->
      <uni-forms-item name="category_id" label="基础分类" required>
        <uni-data-picker
          v-model="formData.category_id"
          :localdata="categoryOptions"
          field="text as text, value as value"
        ></uni-data-picker>
      </uni-forms-item>

      <!-- 所属特殊分类 -->
      <uni-forms-item name="special_category_ids" label="特殊分类">
        <uni-data-picker
          v-model="formData.special_category_ids"
          :localdata="specialCategoryOptions"
          field="text as text, value as value"
          :multiple="true"
    :allow-default-value="true"
        ></uni-data-picker>
      </uni-forms-item>
      <!-- 商品价格 -->
      <uni-forms-item name="price" label="商品价格" required>
        <uni-easyinput
          placeholder="请输入商品价格"
          type="number"
          v-model="formData.price"
        ></uni-easyinput>
      </uni-forms-item>
      <!-- 商品折扣价格 -->
      <uni-forms-item name="discount_price" label="商品折扣价">
        <uni-easyinput
          placeholder="请输入商品折扣价格"
          type="number"
          v-model="formData.discount_price"
        ></uni-easyinput>
      </uni-forms-item>
      <!-- 商品所需积分 -->
      <uni-forms-item name="points" label="商品所需积分">
        <uni-easyinput
          placeholder="请输入商品所需积分"
          type="number"
          v-model="formData.points"
        ></uni-easyinput>
      </uni-forms-item>
      <!-- 商品描述 -->
      <uni-forms-item name="description" label="商品描述">
        <uni-easyinput
          placeholder="请输入商品描述"
          v-model="formData.description"
          trim="both"
        ></uni-easyinput>
      </uni-forms-item>
      <!-- 商品库存 -->
      <uni-forms-item name="stock" label="商品库存">
        <uni-easyinput
          placeholder="请输入商品库存"
          type="number"
          v-model="formData.stock"
        ></uni-easyinput>
      </uni-forms-item>
      <!-- 是否为商品券 -->
      <uni-forms-item name="is_coupon" label="是否为商品券">
        <switch
          @change="binddata('is_coupon', $event.detail.value)"
          :checked="formData.is_coupon"
        ></switch>
      </uni-forms-item>
      <!-- 商品券有效期天数 -->
      <uni-forms-item name="coupon_valid_days" label="商品券有效期">
        <uni-easyinput
          placeholder="请输入商品券有效期天数"
          type="number"
          v-model="formData.coupon_valid_days"
        ></uni-easyinput>
      </uni-forms-item>
      <view class="uni-button-group">
        <button
          type="primary"
          class="uni-button"
          style="width: 100px"
          @click="submit"
        >
          提交
        </button>
        <navigator open-type="navigateBack" style="margin-left: 15px">
          <button class="uni-button" style="width: 100px">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
import { validator } from "../../../../js_sdk/validator/jl_products.js"; // 假设存在验证规则文件

const db = uniCloud.database();
const dbCmd = db.command;
const dbCollectionName = "jl_products";
const storage = uniCloud.uploadFile;

function getValidator(fields) {
  let result = {};
  for (let key in validator) {
    if (fields.includes(key)) {
      result[key] = validator[key];
    }
  }
  return result;
}

export default {
  data() {
    let formData = {
      data_id: "",
      name: "",
      images: [],
      category_id: "",
      special_category_ids: [],
      price: 0,
      discount_price: 0,
      points: 0,
      description: "",
      stock: 0,
      is_coupon: false,
      coupon_valid_days: 0,
    };
    return {
      formData,
      formOptions: {},
      rules: {
        ...getValidator(Object.keys(formData)),
      },
      categoryOptions: [],
      specialCategoryOptions: [],
      isLoading: true, // 添加加载状态
    };
  },
  async onReady() {
    try {
      // 初始化时加载分类数据
      await this.loadCategories();
      await this.loadSpecialCategories();
      this.$refs.form.setRules(this.rules);
      this.isLoading = false;
    } catch (error) {
      console.error("初始化失败:", error);
    }
  },
  methods: {
    // 恢复分类加载方法（仅加载一次）
    async loadCategories() {
      const res = await db
        .collection("jl_product_categories")
        .where({ type: "基础分类" })
        .get();
      this.categoryOptions = res.result.data.map((item) => ({
        text: item.name,
        value: item._id,
      }));
    },
    async loadSpecialCategories() {
      const res = await db
        .collection("jl_product_categories")
        .where({ type: "特殊分类" })
        .get();
      this.specialCategoryOptions = res.result.data.map((item) => ({
        text: item.name,
        value: item._id,
      }));
    },

    // 删除 filterCategoryChange 和 filterSpecialCategoryChange 方法
    async uploadImages(e) {
      const uploadedImages = [];
      for (let file of e) {
        const { fileID } = await storage({
          cloudPath: `products/${new Date().getTime()}-${file.name}`,
          filePath: file.path,
        });
        uploadedImages.push(fileID);
      }
      this.formData.images = uploadedImages;
    },
    binddata(key, value) {
      this.formData[key] = value;
    },
    filterCategoryChange(e) {
      this.formData.category_id = e.value;
    },
    filterSpecialCategoryChange(e) {
      this.formData.special_category_ids = e.value;
    },
    /**
     * 验证表单并提交
     */
    async submit() {
      uni.showLoading({
        mask: true,
      });
      try {
        await this.$refs.form.validate();
        await this.submitForm(this.formData);
        uni.showToast({
          title: "新增成功",
        });
        this.getOpenerEventChannel().emit("refreshData");
        setTimeout(() => uni.navigateBack(), 500);
      } catch (error) {
        uni.showModal({
          content: error.message || "请求服务失败",
          showCancel: false,
        });
      } finally {
        uni.hideLoading();
      }
    },
    /**
     * 提交表单
     */
    async submitForm(value) {
      return db.collection(dbCollectionName).add(value);
    },
  },
};
</script>

<style lang="scss" scoped>
.uni-container {
  padding: 30rpx;
}
.uni-button-group {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
}
</style>
